import json
import os

# Function to ensure students.json exists
if not os.path.exists('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json'):
    with open('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json', 'w', encoding='utf-8') as file:
        file.write('{"students": []}')

# Custom Student class
class Student:
    def __init__(self, username, fullName, age, school, interests, relations, followed_courses):
        self.username = username
        self.fullName = fullName
        self.age = age
        self.school = school
        self.interests = interests
        self.relations = relations
        self.followed_courses = followed_courses

    def add_friend(self, new_friend_username):
        if new_friend_username not in self.relations:
            self.relations.append(new_friend_username)
            self.relations = list(set(self.relations))  # Remove duplicates

            # Update the JSON file
            try:
                with open('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json', 'r', encoding='utf-8') as file:
                    data = json.load(file)

                # Update the current student's relations
                for student in data['students']:
                    if student['username'] == self.username:
                        student['relations'] = self.relations

                # Update the new friend's relations
                for student in data['students']:
                    if student['username'] == new_friend_username:
                        if self.username not in student['relations']:
                            student['relations'].append(self.username)

                with open('C:/Users/lenovo/Desktop/ressources/social_network_system/students.json', 'w', encoding='utf-8') as file:
                    json.dump(data, file, indent=4, ensure_ascii=False)  # Write formatted JSON

            except FileNotFoundError:
                print("students.json file does not exist.")
            except Exception as e:
                print(f"Error occurred while updating the file: {e}")

    def get_friends(self, all_students):
        return [student for student in all_students if student.username in self.relations]


# Custom data structure for managing students
class StudentNode:
    def __init__(self, student):
        self.student = student
        self.next = None

class StudentLinkedList:
    def __init__(self):
        self.head = None

    def add(self, student):
        new_node = StudentNode(student)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node

    def find(self, username):
        current = self.head
        while current:
            if current.student.username == username:
                return current.student
            current = current.next
        return None

    def filter_by_interest(self, interest):
        result = []
        current = self.head
        while current:
            if interest in current.student.interests:
                result.append(current.student)
            current = current.next
        return result

    def to_list(self):
        result = []
        current = self.head
        while current:
            result.append(current.student)
            current = current.next
        return result

# Replace StudentList with StudentLinkedList
class StudentList:
    def __init__(self):
        self.students = StudentLinkedList()

    def add_student(self, student):
        if not self.students.find(student.username):
            self.students.add(student)
            print(f"Successfully added student {student.fullName}")
        else:
            print(f"Student {student.fullName} already exists, not added again.")

    def find_student_by_username(self, username):
        return self.students.find(username)

    def filter_students_by_interest(self, interest):
        return self.students.filter_by_interest(interest)

    def create_community(self, member_usernames):
        return [self.find_student_by_username(username) for username in member_usernames if self.find_student_by_username(username)]

    def find_bridges(self, community1, community2):
        bridges = []
        for student1 in community1:
            for student2 in community2:
                if student2.username in student1.relations:
                    if student1 not in bridges:
                        bridges.append(student1)
                    if student2 not in bridges:
                        bridges.append(student2)
        return bridges


# Function to parse the JSON file using json.load
def parse_student_file(file_path):
    students = []
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)  # Use json.load to directly parse the JSON file

        for student_data in data.get('students', []):
            student = Student(
                username=student_data['username'],
                fullName=student_data['fullName'],
                age=student_data['age'],
                school=student_data['school'],
                interests=student_data['interests'],
                relations=student_data['relations'],
                followed_courses=student_data['followed_courses']
            )
            students.append(student)
    except FileNotFoundError:
        print(f"File {file_path} does not exist.")
    except json.JSONDecodeError as e:
        print(f"Error occurred while parsing the JSON file: {e}")
    except Exception as e:
        print(f"Error occurred while parsing the file: {e}")
    return students
